<template>
  <div>
    <input type="file" @change="handleFileChange" />
    <button @click="uploadFile">上传文件</button>
    <div v-if="uploadProgress > 0">
      <p>上传进度: {{ uploadProgress }}%</p>
      <progress :value="uploadProgress" max="100"></progress>
      <p>上传速度: {{ uploadSpeed }} KB/s</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      file: null,
      chunkSize: 5 * 1024 * 1024, // 5MB
      uploadId: '',
      bucketName: 'zhangzong',
      keyName: '',
      partETagList: [],
      uploadProgress: 0,
      uploadSpeed: 0
    };
  },

  methods: {
    handleFileChange(event) {
      this.file = event.target.files[0];
      this.keyName = this.file.name;
    },
    async initMultipartUpload() {
      const response = await axios.get(this.$https + '/api/minio', {
        params: {
          KeyName: this.keyName
        }
      });
      this.uploadId = response.data;
      // 缓存 uploadId 和 keyName
      localStorage.setItem(this.keyName,this.uploadId);
    },
    async getUploadedParts() {
      const response = await axios.get(this.$https + '/minio/ListPartsFile', {
        params: {
          UploadId: this.uploadId,
          Name: this.keyName
        }
      });
      this.partETagList = response.data.listPartResponse || [];
    },
    async uploadFile() {
      if (!this.file) {
        alert('请选择文件');
        return;
      }
         debugger
      if (!localStorage.getItem(this.keyName)) {
        await this.initMultipartUpload();
      }
      else{
        this.uploadId = localStorage.getItem(this.keyName);
      }
      await this.getUploadedParts();
   console.log(this.partETagList);
  
      const totalChunks = Math.ceil(this.file.size / this.chunkSize); // 计算文件的总块数

      for (let chunkCount = 1; chunkCount <= totalChunks; chunkCount++) {
        if (this.partETagList.some(part => part.partNumber === chunkCount)) {
          // 如果该分片已经上传，跳过
          continue;
        }

        const start = (chunkCount - 1) * this.chunkSize;
        const end = Math.min(this.file.size, start + this.chunkSize);
        const chunk = this.file.slice(start, end);

        const formData = new FormData();
        formData.append('Name', this.keyName);
        formData.append('Size', this.file.size);
        formData.append('partSize', chunk.size);
        formData.append('ChunkCount', chunkCount);
        formData.append('UploadId', this.uploadId);
        formData.append('files', chunk);

        const startTime = Date.now();

        try {
          const response = await axios.post(this.$https + '/minio/ChunkUploadFile', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          });

          const endTime = Date.now();
          const duration = (endTime - startTime) / 1000; // 计算上传时间（秒）
          const speed = (chunk.size / 1024) / duration; // 计算上传速度（KB/s）
          this.uploadSpeed = speed.toFixed(2); // 保留两位小数

          this.partETagList.push(...response.data.partETagList);

          // 更新上传进度
          this.uploadProgress = Math.round((chunkCount / totalChunks) * 100);
        } catch (error) {
          console.error('上传失败:', error);
          alert('上传失败，请重试');
          return;
        }
      }

      await this.completeMultipartUpload();
      alert('文件上传成功');
      this.uploadProgress = 0; // 重置进度条
      this.uploadSpeed = 0; // 重置上传速度
      // 清除缓存
      localStorage.removeItem(this.keyName);
      this.uploadId = '';
      this.keyName = '';
      this.partETagList = [];

    },
    async completeMultipartUpload() {
    
      await axios.post(this.$https + '/minio/ChunkMultipartUpload', {
        uploadId: this.uploadId,
        name: this.keyName,
        partETagList: this.partETagList
      });
    
    }
  }
};
</script>